import { useState } from 'react'
import styles from './index.module.scss'
import * as Yup from 'yup'
import { http, setToken } from '../../utils'
import { useFormik } from 'formik'
import { Toast } from 'antd-mobile'

let timeId = -1

const Login = ({ history }) => {

    const [time, setTime] = useState(-1)
    // }
    // 定义一个变量,用来判断登录是否为第一次点击
    // const isFirst = Object.keys(touched).length === 0
    const formik = useFormik({
        initialValues: {
            mobile: '',
            code: ''
        },
        // 表单验证,我们使用yup这个包来进行验证
        validationSchema: Yup.object({
            // 参数
            mobile: Yup.string()
                .required('手机号为必填项')
                .matches(/^1[3-9]\d{9}$/, '手机号码格式不正确 '),
            code: Yup.string()
                .required('验证码为必填项')
                .matches(/^\d{6}$/, '验证码不正确')
        }),
        onSubmit: async values => {
            try {
                const res = await http.post(
                    'http://geek.itheima.net/v1_0/authorizations',
                    values
                )
                if (res.data.message.toLowerCase() === 'ok') {
                    Toast.info('登陆成功', 1, () => {
                        // 跳转到登录页面
                        history.push('/home')
                        // 把token存储本地储存中
                        setToken(res.data.data)
                    })
                }
            } catch (e) {
                console.dir(e)
                Toast.info(e.response.data.message, 2)
            }
        }
    })
    // 处理表单的提交事件
    const {
        handleSubmit,
        handleBlur,
        handleChange,
        values: { mobile, code },
        // 表示当前表单是否获得焦点过
        touched,
        // 验证失败时的错误信息
        errors,
        isValid
    } = formik
    // 发送请求获取验证码
    const getCode = async () => {
        // console.log(mobile);

        if (time > 0) return
        setTime(59)
        clearInterval(timeId)
        timeId = setInterval(() => {
            setTime(time => {
                if (time === 1) {
                    clearInterval(timeId)
                }
                return time - 1
            })
            // console.log(time);
        }, 1000);
        if (!/^1[3-9]\d{9}$/.test(mobile)) return

        try {
            const res = await http.get(`http://geek.itheima.net/v1_0/sms/codes/${mobile}`)
            // console.log(res);
        } catch (e) { }

    }
    const isFirst = Object.keys(touched).length === 0
    return (
        <div className={styles.root}>
            <h1 className='title'>账号登录</h1>
            <form onSubmit={handleSubmit}>
                <div className="form-item">
                    <input
                        name='mobile'
                        type="text"
                        placeholder='请输入用户名'
                        value={mobile}
                        onBlur={handleBlur}
                        onChange={handleChange}
                    />
                    {touched.mobile && errors.mobile ? (
                        <div className='red'>{errors.mobile}</div>
                    ) : null}
                </div>
                <div className="form-item">
                    <input
                        name='code'
                        type="text"
                        placeholder='请输入验证码'
                        value={code}
                        onBlur={handleBlur}
                        onChange={handleChange}
                    />
                    <span
                        onClick={getCode}
                        className='send-text'
                    >{time <= 0 ? '发送验证码' : `${time}s`}</span>
                    {touched.code && errors.code ? (
                        <div className='red'>{errors.code}</div>
                    ) : null}
                </div>
                <div className="form-item">
                    <button
                        type='submit'
                        // className='active'
                        disabled={isFirst || !isValid}
                        className={isFirst ? '' : (
                            isValid ? 'active' : ''
                        )}
                    >登录</button>
                </div>
            </form>
        </div>
    )
}

export default Login
